---
name: trivy-images
on:
  push:
    branches:
    - main
  schedule:
  - cron: "37 19 * * *"
permissions:
  contents: read
jobs:
  get-dev-image:
    uses: ./.github/workflows/get_image.yaml
    with:
      image-base-name: "dev_image_with_extras"
  image-scan:
    strategy:
      fail-fast: false
      matrix:
        artifact: [cloud, operator, vizier]
    runs-on: ubuntu-latest-8-cores
    needs: get-dev-image
    container:
      image: ${{ needs.get-dev-image.outputs.image-with-tag }}
    permissions:
      actions: read
      contents: read
      security-events: write
    steps:
    - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3  # v3.5.0
    - name: Add pwd to git safe dir
      run: git config --global --add safe.directory `pwd`
    - name: Use github bazel config
      uses: ./.github/actions/bazelrc
      with:
        download_toplevel: 'true'
        BB_API_KEY: ${{ secrets.BB_IO_API_KEY }}
    - name: Build images
      run: |
        ./scripts/bazel_ignore_codes.sh build \
        --//k8s:image_version=nightly --config=x86_64_sysroot \
        //k8s/${{ matrix.artifact }}:image_bundle.tar //k8s/${{ matrix.artifact }}:list_image_bundle
    - name: Load Images
      run: |
        docker load -i bazel-bin/k8s/${{ matrix.artifact }}/image_bundle.tar
    - name: Scan Images
      # yamllint disable rule:line-length
      run: |
        mkdir -p sarif/${{ matrix.artifact }}
        ./bazel-bin/k8s/${{ matrix.artifact }}/list_image_bundle | xargs -I{} sh -c 'trivy image {} --format=sarif --output=sarif/${{ matrix.artifact }}/$(basename {} | cut -d":" -f1).sarif'
      # yamllint enable rule:line-length
    # yamllint disable rule:indentation
    - run: |
        for f in "sarif/${{ matrix.artifact }}/"*; do
          jq '.runs[].tool.driver.name = "trivy-images"' < "$f" > tmp
          mv tmp "$f"
        done
    # yamllint enable rule:indentation
    - uses: github/codeql-action/upload-sarif@04df1262e6247151b5ac09cd2c303ac36ad3f62b  # v2.2.9
      with:
        sarif_file: sarif/${{ matrix.artifact }}
        category: trivy-images
